package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.ConclusionEnum;
import com.tanhua.dubbo.enums.CoverEnum;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.server.vo.ConclusionVo;
import com.tanhua.server.vo.OptionsVo;
import com.tanhua.server.vo.PaperListVo;
import com.tanhua.server.vo.QuestionsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
@Slf4j
@SuppressWarnings("ALL")
public class TestSoulService {
   @DubboReference(version = "1.0.0")
   private SoulReportApi soulReportApi;
    @DubboReference(version = "1.0.0")
    private SoulOptionsApi soulOptionsApi;
    @DubboReference(version = "1.0.0")
    private SoulPaperApi soulPaperApi;
    @DubboReference(version = "1.0.0")
    private SoulPaperQuestionApi soulPaperQuestionApi;
    @DubboReference(version = "1.0.0")
    private SoulQuestionApi soulQuestionApi;


    @Autowired
    private UserInfoApi UserInfoApi;

    /**
     * @MethodName: getReport
     * @Description: 测灵魂-查看结果
     */
    public ConclusionVo getReport(String id) {
        //创建ConclusionVo对象
        ConclusionVo conclusionVo = new ConclusionVo();
        // 获取报告
        SoulReport soulReport = soulReportApi.selectOne(id);
        //如果report表中没有数据,返回null
        if (null == soulReport) {
            return null;
        }
        // 获取成绩
        Long score = soulReport.getScore();
        // 查询分数相近的人
        QueryWrapper<SoulReport> queryListWrapper = new QueryWrapper<>();
        queryListWrapper.between("score", score - 10, score + 10).ne("userid",soulReport.getUserid()).eq("paperid",soulReport.getPaperid());

        List<SoulReport> soulReportList = soulReportApi.selectList(score,soulReport);

        // 获取分数相近的人的 userIdList
        List<Object> userIdList = CollUtil.getFieldValues(soulReportList, "userid");
        //获取userinfoList
        List<UserInfo> userInfoList = new ArrayList<>();
        if (CollUtil.isNotEmpty(userIdList)) {
            userInfoList = UserInfoApi.queryUserInfoByUserIdList(userIdList);
        }
        // 遍历 userInfoList,填充 SoulSimilarYou
        List<SoulSimilarYou> similarYouList = new ArrayList<>();
        if (null != userInfoList) {
            for (UserInfo userInfo : userInfoList) {
                SoulSimilarYou soulSimilarYou = new SoulSimilarYou();
                soulSimilarYou.setAvatar(userInfo.getLogo());
                soulSimilarYou.setId(Convert.toInt(userInfo.getId()));
                similarYouList.add(soulSimilarYou);
            }
        }
        if (21 > score) {
            // <21
            conclusionVo.setConclusion(ConclusionEnum.OWI.toString());
            conclusionVo.setCover(CoverEnum.OWI.toString());
            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("内向", "70%");
            SoulDimensions s2 = new SoulDimensions("理性", "75%");
            SoulDimensions s3 = new SoulDimensions("判断", "80%");
            SoulDimensions s4 = new SoulDimensions("可靠", "60%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        } else if (21 <= score && score <= 40) {
            //21-40
            conclusionVo.setConclusion(ConclusionEnum.RABBIT.toString());
            conclusionVo.setCover(CoverEnum.RABBIT.toString());

            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("稳定", "70%");
            SoulDimensions s2 = new SoulDimensions("友善", "75%");
            SoulDimensions s3 = new SoulDimensions("耐心", "80%");
            SoulDimensions s4 = new SoulDimensions("可靠", "80%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        } else if (41 <= score && score <= 55) {
            //41-55
            conclusionVo.setConclusion(ConclusionEnum.FOX.toString());
            conclusionVo.setCover(CoverEnum.FOX.toString());
            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("外向", "70%");
            SoulDimensions s2 = new SoulDimensions("自信", "75%");
            SoulDimensions s3 = new SoulDimensions("乐观", "80%");
            SoulDimensions s4 = new SoulDimensions("热情", "60%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        } else if (score > 56) {
            // >56
            conclusionVo.setConclusion(ConclusionEnum.LION.toString());
            conclusionVo.setCover(CoverEnum.LION.toString());
            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("外向", "80%");
            SoulDimensions s2 = new SoulDimensions("自信", "85%");
            SoulDimensions s3 = new SoulDimensions("果断", "80%");
            SoulDimensions s4 = new SoulDimensions("强势", "90%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        }
        return conclusionVo;
    }

    /**
     * 测灵魂-问卷列表
     *
     * @return
     */
    public List<PaperListVo> queryPaperList() {

        // 显示的测试试题页面
        PaperListVo paperListVo1 = new PaperListVo();
        PaperListVo paperListVo2 = new PaperListVo();
        PaperListVo paperListVo3 = new PaperListVo();


        //确认这个用户之前是否有答题的报告
        List<SoulReport> soulReports = soulReportApi.selectList(UserThreadLocal.get());
        int size = soulReports.size();
        commendMethod1(paperListVo1, 1);
        commendMethod1(paperListVo2, 2);
        commendMethod1(paperListVo3, 3);

        //判断报告id是否为空,是初级的
        if (size == 0) {
            // 解除初级锁定
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(1);
            paperListVo3.setIsLock(1);

        } else if (soulReports.size() == 1) {
            // 解除中级锁定
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(1);
        } else if (soulReports.size() == 2) {
            // 解除高级锁定
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(0);
        }

        //返回测试试题页面
        List<PaperListVo> list = new ArrayList<>();
        list.add(paperListVo1);
        list.add(paperListVo2);
        list.add(paperListVo3);

        return list;
    }

    //形成试题
    private void commendMethod1(PaperListVo paperListVo, int i) {
        //设置编号
        paperListVo.setId(String.valueOf(i));
        //设置名称
        paperListVo.setName(soulPaperApi.selectById(i).getName());
        //设置封面
        paperListVo.setCover(soulPaperApi.selectById(i).getCover());
        //设置级别
        paperListVo.setLevel(soulPaperApi.selectById(i).getLevel());
        //设置星别
        paperListVo.setStar(Convert.toInt(soulPaperApi.selectById(i).getStar()));

        List<SoulPaperQuestion> soulPaperQuestions = soulPaperQuestionApi.selectList(i);

        List<QuestionsVo> questionsVoList = new ArrayList<>();
        //遍历题目
        for (SoulPaperQuestion soulPaperQuestion : soulPaperQuestions) {
            //把题目加入QuestionsVo对象
            QuestionsVo questionsVo = new QuestionsVo();
            questionsVo.setId(soulPaperQuestion.getQuestionid().toString());
            questionsVo.setQuestion(soulQuestionApi.selectById(soulPaperQuestion.getQuestionid()).getQuestion());

            //得到选项的集合

            List<SoulOptions> soulOptionsList = soulOptionsApi.selectList(soulPaperQuestion.getQuestionid());

            //得到选项的集合
            List<OptionsVo> optionsVolist = new ArrayList<>();

            //得到optionsVolist集合
            for (SoulOptions soulOptions : soulOptionsList) {
                OptionsVo optionsVo = new OptionsVo();
                optionsVo.setId(soulOptions.getId().toString());
                optionsVo.setOption(soulOptions.getOptions());
                optionsVolist.add(optionsVo);
            }
            questionsVo.setOptions(optionsVolist);
            questionsVoList.add(questionsVo);
        }
        // 乱序题目
        Collections.shuffle(questionsVoList);
        paperListVo.setQuestions(questionsVoList);
    }

    /**
     * 提交问卷
     *
     * @param map
     * @return
     */
    public String submitTestPaper(Map<String, List<Answers>> map) {
        //计算得分
        Long score = 0L;
        Long questionid = 0L;
        //遍历获得对象

        Collection<List<Answers>> AnswersList = map.values();
        for (List<Answers> answers : AnswersList) {
            //试题ID
            for (Answers answer : answers) {
                questionid = Long.valueOf(answer.getQuestionId());
                //获得选项的字符串
                String optionId = answer.getOptionId();
                //计算得分
                SoulOptions soulOptions1 = this.soulOptionsApi.selectOne(optionId);
                Long score1 = soulOptions1.getScore();
                score += score1;
            }
        }

        //判断做的是哪套试卷
        SoulPaperQuestion soulPaperQuestion = this.soulPaperQuestionApi.selectOne(questionid);
        Long paperid = soulPaperQuestion.getPaperid();
        // 查询是否已经有了成绩,更新或者插入
        /*QueryWrapper<SoulReport> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("userid", UserThreadLocal.get()).eq("paperid", paperid);*/
        SoulReport result = this.soulReportApi.selectOne(UserThreadLocal.get(),paperid);

        if (ObjectUtil.isNotEmpty(result)) {
            //不为空就更新,最后将ID返回
            SoulReport soulReport = new SoulReport();
            soulReport.setScore(score);
            soulReport.setUpdated(new Date(System.currentTimeMillis()));
            soulReportApi.update(soulReport);

            //查询当前结果的ID返回
            SoulReport soulReport1 = soulReportApi.selectOne(UserThreadLocal.get(), paperid);
            // System.out.println("当前结果的ID为:" + soulReport1.getId());
            return soulReport1.getId().toString();
        }
        //如果查不到那就插入
        SoulReport soulReport = new SoulReport();
        soulReport.setUserid(UserThreadLocal.get());
        soulReport.setPaperid(paperid);
        soulReport.setScore(score);
        soulReport.setCreated(new Date(System.currentTimeMillis()));
        soulReport.setUpdated(new Date(System.currentTimeMillis()));
        soulReportApi.insert(soulReport);

        //查询当前结果的ID返回
        SoulReport soulReport1 = soulReportApi.selectOne(UserThreadLocal.get(),paperid);
        return soulReport1.getId().toString();
    }

}
